#!/usr/bin/env python
# coding:utf-8
from PoboAPI import *
import datetime
import numpy as np

#开始时间，用于初始化一些参数
#多周期共振，用户自己可以去完善换月的部分
def OnStart(context) :
    print("I\'m starting...")
    #登录交易账号，需在主页用户管理中设置账号，并把期货测试替换成您的账户名称
    context.myacc = None
    if "回测期货" in context.accounts :
        print("登录交易账号[回测期货]")
        if context.accounts["回测期货"].Login() :
            context.myacc = context.accounts["回测期货"]

def OnMarketQuotationInitialEx(context, exchange,daynight):
    if exchange != 'SHFE':
        return
    #获取主力合约
    g.code = GetMainContract('SHFE', 'rb',20)
    #订阅K线数据，用于驱动OnBar事件
    SubscribeBar(g.code, BarType.Min5)
    print("target contract "+str(g.code))
    
#实时行情事件，当有新行情出现时调用该事件Ex
def OnBar(context,code,bartype):
    #过滤掉不需要的行情通知
    if code != g.code:
        return
    dyndata = GetQuote(g.code)
    g.open=0
    g.close=0
    
    posdaysleft=200
    
    #查持仓
    
    option = PBObj()
    #option.buysellflag = '0'
    positions = context.myacc.GetPositions(option)
    
    if len(positions)>0:
        
        posdaysleft=GetTradingDayLeft(positions[0].contract)
    
        #print("posdaysleft "+str(posdaysleft))
    
    
    #计算均线
    MADay = GetIndicator("MA",code,params=(3,6),bar_type = BarType.Day)
    MA1Day = MADay["MA(3)"]
    MA2Day = MADay["MA(6)"]
    if len(MA2Day)<2:
        return
    #ma1上穿ma2时买入螺纹主力1手
    elif MA1Day[-1] >= MA2Day[-1] and MA1Day[-2]<MA2Day[-2]:
        print("day ma condition met")
        g.open=g.open+1
    #ma1下穿ma2时卖出平仓
    elif MA1Day[-1] <= MA2Day[-1] and MA1Day[-2]>MA2Day[-2]:
        print("day ma condition met")
        g.close=g.close+1
        
        
    MAHour = GetIndicator("MA",code,params=(4,8),bar_type = BarType.Min60)
    MA1Hour = MAHour["MA(4)"]
    MA2Hour = MAHour["MA(8)"]
    if len(MA2Hour)<2:
        return
    #ma1上穿ma2时买入螺纹主力1手
    elif MA1Hour[-1] >= MA2Hour[-1] and MA1Hour[-2]<MA2Hour[-2]:
        print("hour ma condition met")
        g.open=g.open+1
    #ma1下穿ma2时卖出平仓
    elif MA1Hour[-1] <= MA2Hour[-1] and MA1Hour[-2]>MA2Hour[-2]:
        print("hour ma condition met")
        g.close=g.close+1
    
    MAMin = GetIndicator("MA",code,params=(5,10),bar_type = BarType.Min5)
    MA1Min = MAMin["MA(5)"]
    MA2Min = MAMin["MA(10)"]
    if len(MA2Min)<2:
        return
    #ma1上穿ma2时买入螺纹主力1手
    elif MA1Min[-1] >= MA2Min[-1] and MA1Min[-2]<MA2Min[-2]:
        print("minute ma condition met")
        g.open=g.open+1
        #QuickInsertOrder(context.myacc,g.code,'buy','open',dyndata.now,10)
    #ma1下穿ma2时卖出平仓
    elif MA1Min[-1] <= MA2Min[-1] and MA1Min[-2]>MA2Min[-2]:
        print("minute ma condition met")
        g.close=g.close+1
        #QuickInsertOrder(context.myacc,g.code,'sell','close',dyndata.now,10)
        
    if g.open>=3:
        
        print("g.open "+str(g.open)) 
        
        QuickInsertOrder(context.myacc,g.code,'buy','open',dyndata.now,30)
        
    if g.close>=3 or posdaysleft<10:
        
        print("g.close "+str(g.close)) 
        
        QuickInsertOrder(context.myacc,g.code,'sell','close',dyndata.now,30)
        
def GetTradingDayLeft(code):
    import re 
    m=re.match(r'[a-z]+[0-9]+\.+[A-Z]',code)
    if m:
      info=GetContractInfo(code) 
      T=info['最后交易日']
      exchange=GetExchangeByCode(code)
      t=GetCurrentTradingDate(exchange)
      return (T-t).days
    else:
      info=GetContractInfo(code) 
      T=info['行权到期日']
      exchange=GetExchangeByCode(code)
      t=GetCurrentTradingDate(exchange)
      return (T-t).days
        
